package com.shu.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.google.common.collect.Lists;
import com.shu.dto.User;
import com.shu.dto.UserQueryCondition;
import com.shu.exception.UserNotExistException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shujinhao
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping
    @JsonView(User.UserSimpleView.class)
    public List<User> query(UserQueryCondition condition,@PageableDefault(page = 1,size = 10,sort = "username,asc") Pageable pageable){
        System.out.println(condition.toString());
        log.error(pageable.getPageSize()+"");
        log.error(pageable.getSort()+"");
        log.error(pageable.getPageNumber()+"");

        List<User> userList = Lists.newArrayList();
        User user = new User();
        user.setPassword("bbbb");
        user.setUsername("小明");
        userList.add(user);
        userList.add(user);
        userList.add(user);
        return userList;
    }

    //正则表达式，只能是数字
    @GetMapping("/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable(value = "id") String id){

//        throw  new UserNotExistException(id);
        log.error("调用getInfo服务");
        User user = new User();
        user.setUsername("tom");
        user.setPassword("aaa");
        return user;
    }

    @PostMapping
    public User create(@Valid @RequestBody User user, BindingResult errors){
        if (errors.hasErrors()){
            errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
        }
        System.out.println(user.toString());
        user.setId("1");
        return user;
    }

    @PutMapping("/{id:\\d+}")
    public User update(@Valid @RequestBody User user, BindingResult errors){
        if (errors.hasErrors()){
            errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
        }
        System.out.println(user.toString());
        user.setId("1");
        return user;
    }
    @DeleteMapping("/{id:\\d+}")
    public void  delete(@PathVariable String id){
        System.out.println(id);

    }
}
